package cn.zzqayy.steward.gateway.controller;

import cn.zzqayy.steward.gateway.config.UserDetailsServiceImpl;
import cn.zzqayy.steward.gateway.params.LoginParams;
import cn.zzqayy.steward.gateway.utils.JwtUtils;
import cn.zzqayy.steward.ResultJson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zzqayy
 * @date 2020/7/2
 */
@RestController
public class LoginController {

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private UserDetailsServiceImpl userDetailsService;

    /**
     * 登录
     * @param params
     * @return
     */
    @PostMapping("/login")
    public ResultJson<Map<String, String>> login(@RequestBody @Valid LoginParams params){
        UsernamePasswordAuthenticationToken jwtUsernamePasswordToken = new UsernamePasswordAuthenticationToken(params.getUsername(), params.getPassword());
        Authentication authentication = authenticationManager.authenticate(jwtUsernamePasswordToken);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        UserDetails userDetails = userDetailsService.loadUserByUsername(params.getUsername());
        String token = jwtUtils.generateToken(userDetails);
        Map<String, String> result = new HashMap<>(1);
        result.put("token", token);
        return ResultJson.SUCCESS(result);
    }

}
